package se.webbzon.oschi01.resourceset;

import java.util.Iterator;

public class ResourceIterator<R> implements Iterator<R> {
	
	// The resource set attached to this resource iterator
	private final ResourceSet<R> resourceSet;
	
	// The speed and index of the iterator
	private double speed, index;
	
	/*============================================================
	Constructors
	============================================================*/
	
	/** Creates a new resource iterator which wraps the given resource set. **/
	public ResourceIterator(ResourceSet<R> resourceSet) {
		this.resourceSet = resourceSet;
	}
	
	/*============================================================
	Public Methods
	============================================================*/
	
	/** Returns the update speed of the iterator. If speed is equal to
	 * 1 then the output of the iterator will be updated once per call. **/
	public double getSpeed() {
		return speed;
	}
	
	/** Sets the update speed of the iterator. If speed is equal to
	 * 1 then the output of the iterator will be updated once per step. **/
	public void setSpeed(double speed) {
		if (speed >= 0)
			this.speed = speed % resourceSet.size();
	}
	
	/** Returns the resource index of the current iteration.
	 * The real resource index of the iterator is the returned
	 * value floored. */
	public double getIndex() {
		return index;
	}
	
	/** Sets the index of the current iteration.
	 * The real resource index of the iterator is the returned
	 * value floored. */
	public void setIndex(double index) {
		if (index != this.index && index >= 0 && index < resourceSet.size())
			this.index = index;
	}
	
	/** Returns the current element of the iteration. **/
	public R current() {
		return resourceSet.get((int) index);
	}

	@Override public boolean hasNext() {
		return true;
	}

	@Override public R next() {
		if (speed > 0) {
			double index = this.index + speed;
			if (index >= resourceSet.size())
				index -= resourceSet.size();
			this.index = index;
		}
		return resourceSet.get((int) index);
	}

	@Override public void remove() {
		throw new UnsupportedOperationException();
	}

}
